<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Movie;
use App\Models\Comment;
use App\Transformers\CommentTransformer;
use App\Http\Requests\Api\CommentRequest;
use App\Services\Alibaba\Ali;
use Cache;
use Carbon\Carbon;
class CommentsController extends Controller
{
    /**
     * 单个电影的评论
     * @param Movie $movie
     * @return \Dingo\Api\Http\Response
     */
    public function movie(Movie $movie)
    {
        $comments = $movie->comments()->recent()->paginate(20);
        return $this->response->paginator($comments, new CommentTransformer);
    }
    public function index()
    {
        $comments = Comment::where('source', 'douban')->recent()->paginate(20);
        return $this->response->paginator($comments, new CommentTransformer);
    }

    public function show(Movie $movie)
    {

    }
    /**
     * 创建一条评论
     *
     * @param Request $request
     * @return void
     */
    public function store(Movie $movie, Comment $comment, CommentRequest $request)
    {
        if (Cache::has('comment_last_time_' . $this->user()->id)) {
            return $this->error('评论间隔不能小于 1 分钟', 421);
        }
        if (Cache::has('movie_comment_last_time_' . $this->user()->id . '_' . $movie->id)) {
            return $this->error('相同电影评论间隔不能小于 10 分钟', 421);
        }
        $data = $comment->fill($request->all());
        $data['movie_id'] = $movie->id;
        $data['user_id'] = $this->user()->id;
        $data->save();
        // 记录最后评论时间
        Cache::set('comment_last_time_' . $this->user()->id, true, 60);
        Cache::set('movie_comment_last_time_' . $this->user()->id . '_' . $movie->id, true, 60 * 10);
        $comment = Comment::with('author')->find($data->id);
        return $this->response->item($comment, new CommentTransformer);
    }
    public function destroy(Comment $comment)
    {

        // $comment->delete();
        // return $this->response->noContent();
    }
}
